<?php

/*
 * FICHIERS DE FONCTIONS POUR LES USERS
 * 
 */



/*
 * Retire l'accès aux non administrateurs de options du menu
 */
function wpspo_remove_admin_menus() {
	global $menu;
    if ( current_user_can('participant') ) {
        $restricted = array( __('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'), 'Contact');
    } else {
        $restricted = array();
    }
	end ($menu);
 
	while (prev($menu)) {
		$value = explode(' ',$menu[key($menu)][0]);
		if(in_array($value[0] != NULL?$value[0]:"" , $restricted)) {
			unset($menu[key($menu)]);
		}
	}
}
add_action('admin_menu', 'wpspo_remove_admin_menus');

/*
 * Ajout au formulaire d'inscription des champs supplémentaires
 */
//1. Add a new form element...
add_action('register_form','wpspo_register_form');
function wpspo_register_form (){
    $first_name = ( isset( $_POST['first_name'] ) ) ? $_POST['first_name']: '';
    $last_name = ( isset( $_POST['last_name'] ) ) ? $_POST['last_name']: '';
    $photo = ( isset( $_FILES["assoimg"]["name"] ) ) ? $_FILES["assoimg"]["name"]: '';
    $user_birthday_j = ( isset( $_POST['user_birthday_j'] ) ) ? $_POST['user_birthday_j']: '';
    $user_birthday_m = ( isset( $_POST['user_birthday_m'] ) ) ? $_POST['user_birthday_m']: '';
    $user_birthday_a = ( isset( $_POST['user_birthday_a'] ) ) ? $_POST['user_birthday_a']: '';
    ?>
    <p>
        <label><?php _e('Your last name', 'sponsorpress'); ?></label>
			<input id="user_name" type="text" name="last_name" maxlength="30" value="<?php echo esc_attr(stripslashes($last_name)); ?>"  />
			
    </p>
    <p>
        <label for="first_name"><?php _e('Your first name', 'sponsorpress'); ?><br /></label>
            <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr(stripslashes($first_name)); ?>" size="25" />
    </p>
    <p>
        <label for="user_birthday"><?php _e('Your birthday', 'sponsorpress'); ?><br /></label>
        <select name="user_birthday_j" id="user_birthday_j">
            
            <?php
                //echo '<option value="#">'.__('Day', 'sponsorpress').'</option>';
                for($date_jour = 1; $date_jour <= 31; $date_jour++) {
                ?>
                    <option value="<?php echo $date_jour ?>"><?php echo $date_jour?></option>
            <?php
                }
            ?>
        </select>
        <select name="user_birthday_m" id="user_birthday_m">
            <?php
            //echo '<option value="#">'.__('Month', 'sponsorpress').'</option>';
            $mois = array(
                1=>'Janvier', 
                2=>'Février', 
                3=>'Mars',                      
                4=>'Avril', 
                5=>'Mai', 
                6=>'Juin',
                7=>'Juillet',
                8=>'Aout',
                9=>'Septembre',
                10=>'Octobre',
                11=>'Novembre',
                12=>'Decembre'
            );

            foreach($mois as $key => $moi) {
                echo '<option value="' . $key . '">' . $moi . '</option>';
            }
            ?>          
        </select>
        <select name="user_birthday_a" id="user_birthday_a">
            <?php
                //echo '<option value="#">'.__('Year', 'sponsorpress').'</option>';
                for($date_annee = 1920; $date_annee <= (date('Y')-10); $date_annee++) {
               ?>
                    <option value="<?php echo $date_annee ?>"><?php echo $date_annee ?></option>
            <?php
                    }
            ?>
        </select>
    </p>
    <?php
}

//2. Add validation. In this case, we make sure first_name is required.
add_filter('registration_errors', 'wpspo_registration_errors', 10, 3);
function wpspo_registration_errors ($errors, $sanitized_user_login, $user_email) {

    if ( empty( $_POST['first_name'] ) )
        $errors->add( 'first_name_error', __('<strong>ERROR</strong>: You must include a first name.', 'sponsorpress') );
    if ( empty( $_POST['last_name'] ) )
        $errors->add( 'last_name_error', __('<strong>ERROR</strong>: You must include a name.', 'sponsorpress') );
    if ( empty( $_POST['user_birthday_j'] ) )
        $errors->add( 'user_birthday_j_error', __('<strong>ERROR</strong>: You must include you birthday.', 'sponsorpress') );
    if ( empty( $_POST['user_birthday_m'] ) )
        $errors->add( 'user_birthday_m_error', __('<strong>ERROR</strong>: You must include you birthday.', 'sponsorpress') );
    if ( empty( $_POST['user_birthday_a'] ) )
        $errors->add( 'user_birthday_a_error', __('<strong>ERROR</strong>: You must include you birthday.', 'sponsorpress') );
    
    
    return $errors;
}

//3. Finally, save our extra registration user meta.
add_action('user_register', 'wpspo_user_register');
function wpspo_user_register ($user_id) {
    if ( isset( $_POST['first_name'] ) )
        update_user_meta($user_id, 'first_name', $_POST['first_name']);
    if ( isset( $_POST['last_name'] ) )
        update_user_meta($user_id, 'last_name', $_POST['last_name']);
    if ( isset( $_POST['user_birthday_j'] ) )
        update_user_meta($user_id, 'user_birthday_j', $_POST['user_birthday_j']);
    if ( isset( $_POST['user_birthday_m'] ) )
        update_user_meta($user_id, 'user_birthday_m', $_POST['user_birthday_m']);
    if ( isset( $_POST['user_birthday_a'] ) )
        update_user_meta($user_id, 'user_birthday_a', $_POST['user_birthday_a']);
    //update_user_meta( $user_id, 'assoimg', $assofichier);
}

/*
 * Ajoute des champs supplémentaires pour l'user
 */
function wpspo_new_contactmethods( $contactmethods ) {
    $contactmethods['adresse'] = __('Address', 'sponsorpress');
    $contactmethods['adresse2'] = __('Address (cont.)', 'sponsorpress');
    $contactmethods['cp'] = __('Postcode', 'sponsorpress');
    $contactmethods['ville'] = __('City', 'sponsorpress');
    $contactmethods['telephone'] = __('Phone', 'sponsorpress');
    $contactmethods['pays'] = __('Country', 'sponsorpress');
    return $contactmethods;
}
add_filter('user_contactmethods','wpspo_new_contactmethods',10,1);

/*
 * Ajoute des champs supplémentaires pour l'user si Association
 */
add_action( 'show_user_profile', 'contact_user_profile_fields' );
add_action( 'edit_user_profile', 'contact_user_profile_fields' );

function contact_user_profile_fields( $user ) { 
    
    $user_birthday_j = get_user_meta($user->ID, 'user_birthday_j', true);
    $user_birthday_m = get_user_meta($user->ID, 'user_birthday_m', true);
    $user_birthday_a = get_user_meta($user->ID, 'user_birthday_a', true);
?>
<h3><?php _e("Information for participants challenges -  SponsorPress", "sponsorpress"); ?></h3>
<table class="form-table">
    <tr>
        <th><label for="participantdesc"><?php _e('Your birthday', 'sponsorpress'); ?></label>
            <?php //echo 'J:'.$user_birthday_j.'-'.$user_birthday_m.'-'.$user_birthday_a; ?></th>
        <td>
        <select name="user_birthday_j" id="user_birthday_j">
            
            <?php
                //echo '<option value="#">'.__('Day', 'sponsorpress').'</option>';
                
                for($date_jour = 1; $date_jour <= 31; $date_jour++) {
                    if($date_jour==$user_birthday_j) { $addSelectedJ = 'selected="selected"'; } else { $addSelectedJ = ''; }
                ?>
                    <option value="<?php echo $date_jour ?>" <?php echo $addSelectedJ; ?>><?php echo $date_jour?></option>
            <?php
                }
            ?>
        </select>
        <select name="user_birthday_m" id="user_birthday_m">
            <?php
            //echo '<option value="#">'.__('Month', 'sponsorpress').'</option>';
            $mois = array(
                1=>'Janvier', 
                2=>'Février', 
                3=>'Mars',                      
                4=>'Avril', 
                5=>'Mai', 
                6=>'Juin',
                7=>'Juillet',
                8=>'Aout',
                9=>'Septembre',
                10=>'Octobre',
                11=>'Novembre',
                12=>'Decembre'
            );

            foreach($mois as $key => $moi) {
                if($key==$user_birthday_m) { $addSelectedM = 'selected="selected"'; } else { $addSelectedM = ''; }
                echo '<option value="' . $key . '" '.$addSelectedM.'>' . $moi . '</option>';
            }
            ?>          
        </select>
        <select name="user_birthday_a" id="user_birthday_a">
            <?php
                //echo '<option value="#">'.__('Year', 'sponsorpress').'</option>';
                for($date_annee = 1920; $date_annee <= (date('Y')-10); $date_annee++) {
                    if($date_annee==$user_birthday_a) { $addSelectedA = 'selected="selected"'; } else { $addSelectedA = ''; }
               ?>
                    <option value="<?php echo $date_annee ?>" <?php echo $addSelectedA; ?>><?php echo $date_annee ?></option>
            <?php
                    }
            ?>
        </select>
        </td>
    </tr>
</table>

<?php }

add_action( 'personal_options_update', 'save_contact_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_contact_user_profile_fields' );

function save_contact_user_profile_fields( $user_id ) {
 
    if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }

    if( $_POST['user_birthday_j'] ) {  update_user_meta( $user_id, 'user_birthday_j', $_POST['user_birthday_j'] ); }
    if( $_POST['user_birthday_m'] ) {  update_user_meta( $user_id, 'user_birthday_m', $_POST['user_birthday_m'] ); }
    if( $_POST['user_birthday_a'] ) {  update_user_meta( $user_id, 'user_birthday_a', $_POST['user_birthday_a'] ); }
}

/**
 * Fonction pour supprimer le logo
 */
function wpspo_logo_delete( $user_id ) {
    $old_logos = get_user_meta( $user_id, 'wpspo_user_logo', true );
    $upload_path = wp_upload_dir();

    if ( is_array($old_logos) ) {
        foreach ($old_logos as $old_logo ) {
            $old_logo_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $old_logo );
            @unlink( $old_logo_path );	
        }
    }

    delete_user_meta( $user_id, 'wpspo_user_logo' );
}

/**
 * Fonction faire appel au logo et créé la taille si elle n'existe pas
 */
function wpspo_get_user_logo( $userId, $size = 96, $default = '' ) {
    
    if ( empty( $userId ) ) { return $logo; }
    $local_logos = get_user_meta( $userId, 'wpspo_user_logo', true );
    $size = (int) $size;

    if ( empty( $local_logos[$size] ) && !empty($local_logos['full']) ) {
        
        $upload_path = wp_upload_dir();
        $logo_full_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $local_logos['full'] );
        $image_sized = image_resize( $logo_full_path, $size, $size, true );		
        // deal with original being >= to original image (or lack of sizing ability)
        $local_logos[$size] = is_wp_error($image_sized) ? $local_logos[$size] = $local_logos['full'] : str_replace( $upload_path['basedir'], $upload_path['baseurl'], $image_sized );
        // save updated avatar sizes
        update_user_meta( $userId, 'wpspo_user_logo', $local_logos );

    } elseif ( substr( $local_logos[$size], 0, 4 ) != 'http' ) {
        $local_logos[$size] = home_url( $local_logos[$size] );
    }
    if( $local_logos[$size] ) {
        return "<img alt='" . esc_attr( $alt ) . "' src='" . $local_logos[$size] . "' class='' height='{$size}' width='{$size}' />";    
    } else {
        return '';
    }
}

/*
 * Récupère le role de l'user connecté
 *
 */
function wpspo_get_user_role() {
    
    global $current_user;
	$user = new WP_User( $current_user->ID );
    $user_role = array_shift($user->roles);
    return translate_user_role( $user_role );
    
}
/*
 * Récupère le role de l'user connecté via ID
 *
 */
function wpspo_get_user_role_by_id( $user_id ) {
	
    $user = new WP_User( $user_id );
    $user_role = array_shift($user->roles);
    return translate_user_role( $user_role );
 
}

/*
 * Tableau des roles 
 */
function wpspo_get_name_role($user_role) {
    $tabRole = array(
        'Participant'=>'participant'
        );
    return array_search($user_role, $tabRole);
}

/* DERNIERS INSCRITS*/
function wpspo_list_users($limit = 10) {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $seachRole = 'a:1:{s:11:"participant";b:1;}';
    $authorParticipant = $wpdb->get_results("SELECT * from $wpdb->usermeta WHERE meta_key = '".$prefix."capabilities' AND meta_value = '".$seachRole."' ORDER BY umeta_id DESC LIMIT ".$limit."");
    foreach ( (array) $authorParticipant as $author ) {
		$author    = get_userdata( $author->user_id );
		$userlevel = $author->wp2_user_level;
		$name      = $author->nickname;
		if ( $show_fullname && ($author->first_name != '' && $author->last_name != '') ) {
			$name = "$author->first_name $author->last_name";
		}
		$link = $name;
	}
    return $link;
}

if (!function_exists('wspo_affiche_user')) {  
    
    function wspo_affiche_user($user_id, $link = 1) {
        
        $userParticipant = get_userdata($user_id);
        $first_name = $userParticipant->user_firstname;
        $last_name = $userParticipant->user_lastname;
        $nameParticipant = $first_name.' '.$last_name;
        $nameParticipant = $userParticipant->display_name;
        if($first_name=='' && $last_name=='') { 
            $nameParticipant = ucfirst($userParticipant->display_name); 
        }
        if($link == 1) {
            return '<a href="'. get_permalink(WPSPO_ID_PARTICIPANTS).'?profil='.get_the_author_meta( 'user_nicename', $user_id).'">'.$nameParticipant.'</a>';
        } else {
            return $nameParticipant;
        }
    }
    
}

if (!function_exists('wspo_affiche_age')) {  
    
    function wspo_affiche_age($user_id) {
        //global $wpdb;
        $user = get_user_meta($user_id);
        $date = $user['user_birthday_a'][0].'-'.$user['user_birthday_m'][0].'-'.$user['user_birthday_j'][0];
        if($user['user_birthday_j'][0]>0) {
            $d = strtotime($date);
            return (int) ((time() - $d) / 3600 / 24 / 365.242);
        } else {
            return '';
        }    
    }
}
